package com.sc.smartcommunity.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.smartcommunity.domain.Payment;
import com.sc.smartcommunity.domain.PaymentOrder;
import com.sc.smartcommunity.domain.PaymentRecord;
import com.sc.smartcommunity.mapper.PaymentMapper;
import com.sc.smartcommunity.mapper.PaymentOrderMapper;
import com.sc.smartcommunity.service.PaymentRecordService;
import com.sc.smartcommunity.service.PaymentService;
import com.sc.smartcommunity.domain.vo.OrderNoGenerator;
import com.sc.smartcommunity.domain.vo.PaymentDetailVO;
import com.sc.smartcommunity.domain.vo.PaymentVO;
import com.sc.smartcommunity.domain.vo.ResultVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Resource
    private PaymentOrderMapper paymentOrderMapper;
    @Resource
    private PaymentRecordService paymentRecordService;


    @Override
    @Transactional
    public ResultVO createPayment(PaymentVO paymentVO) {
        String loginId = StpUtil.getLoginIdAsString();
        // 创建缴费记录
        Payment payment = new Payment();
        BeanUtils.copyProperties(paymentVO, payment);
        payment.setStatus(0); // 初始状态：未支付
        baseMapper.insert(payment); // 仅插入一次payment

        // 创建缴费订单
        PaymentOrder order = new PaymentOrder();
        order.setPaymentId(payment.getId()); // 使用第一次插入后生成的id
        order.setOrderNo(OrderNoGenerator.generate()); // 生成唯一订单号


        paymentOrderMapper.insert(order); // 插入订单记录

        paymentRecordService.addPaymentRecord(new PaymentRecord(null, paymentVO.getPaymentType(), paymentVO.getAmount(), 0, loginId, LocalDateTime.now()));
        return ResultVO.success(order.getOrderNo());
    }
    @Override
    public ResultVO getUserPayments(Long userId, Integer page, Integer size) {
        Page<Payment> pagination = new Page<>(page, size);
        QueryWrapper<Payment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .orderByDesc("created_time");

        IPage<Payment> paymentPage = baseMapper.selectPage(pagination, queryWrapper);
        return ResultVO.success(paymentPage);
    }

    @Override
    @Transactional
    public ResultVO payOrder(Long paymentId, Integer payChannel) {
        // 查询缴费记录
        Payment payment = baseMapper.selectById(paymentId);
        if (payment == null) {
            return ResultVO.fail("缴费记录不存在");
        }

        // 检查状态
        if (payment.getStatus() == 1) {
            return ResultVO.fail("该订单已支付");
        }

        // 更新缴费状态
        payment.setStatus(1);
        payment.setPaymentTime(LocalDateTime.now());
        baseMapper.updateById(payment);

        // 更新订单信息
        QueryWrapper<PaymentOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("payment_id", paymentId);
        PaymentOrder order = paymentOrderMapper.selectOne(queryWrapper);

        if (order != null) {
            order.setPayChannel(payChannel);
            order.setPayNo(generatePayNo()); // 模拟生成支付流水号
            paymentOrderMapper.updateById(order);
        }

        return ResultVO.success("支付成功");
    }

    @Override
    public ResultVO getPaymentDetail(Long paymentId) {
        Payment payment = baseMapper.selectById(paymentId);
        if (payment == null) {
            return ResultVO.fail("缴费记录不存在");
        }

        QueryWrapper<PaymentOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("payment_id", paymentId);
        PaymentOrder order = paymentOrderMapper.selectOne(queryWrapper);

        return ResultVO.success(new PaymentDetailVO(payment, order));
    }

    // 模拟生成支付流水号
    private String generatePayNo() {
        return "PAY" + System.currentTimeMillis() + (int)(Math.random() * 1000);
    }
}
